package com.wxxymaker.controller;

import com.wxxymaker.service.ExcelService;
import com.wxxymaker.utils.web.ResponseWarp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Author: Soft
 * @Date: 2018/5/13 17:39
 * @Desc: 系统下所有excel导入导出操作接口
 */
@Controller
@RequestMapping("/excel")
public class ExcelHandler {
    private final static Logger log = LoggerFactory.getLogger(ExcelHandler.class);

    private final ExcelService excelService;

    @Autowired
    public ExcelHandler(ExcelService excelService) {
        this.excelService = excelService;
    }

    @GetMapping("/export/user")
    public void exportUser(@RequestParam(defaultValue = "0") Integer post,
                           HttpServletRequest request,
                           HttpServletResponse response) throws UnsupportedEncodingException {
        ServletContext context = request.getServletContext();
        File output = new File(context.getRealPath("/WEB-INF/static/excel/UserInfoTable.xls"));
        try {
            excelService.outputUser(post, output);
        } catch (Exception e) {
            log.debug("{}", e);
            log.error("导出用户Excel表失败！--> {}", e.getMessage());
        }
        try {
            this.sendFile(output, response);
        } catch (IOException e) {
            log.debug("{}", e);
            log.error("文件发送失败！--> {}", e.getMessage());
        }
    }

    @PostMapping("/import/user")
    @ResponseBody
    public ResponseWarp importUser(@RequestParam String filename,
                                   HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        File input = new File(context.getRealPath("/WEB-INF/static/" + filename));
        try {
            excelService.inputUser(input);
            return ResponseWarp.ok("导入成功！");
        } catch (Exception e) {
            log.debug("{}", e);
            log.error("用户信息导入失败！--> {}", e.getMessage());
        }
        return ResponseWarp.error("导入失败！Excel格式可能不对！");
    }

    /**
     * 导出阶段统计记录
     * @param stageId  阶段id
     * @param shopId   公司id
     * @param detail   是否导出详细内容
     */
    @GetMapping("/export/stageCount")
    public void exportStageCount(@RequestParam(defaultValue = "0") Integer stageId,
                                 @RequestParam(defaultValue = "0") Integer shopId,
                                 @RequestParam(defaultValue = "1") boolean detail,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        ServletContext context = request.getServletContext();
        File output = new File(context.getRealPath("/WEB-INF/static/excel/StageMarkCountTable.xls"));
        try {
            excelService.outputStageCount(output, stageId, shopId, detail);
        } catch (Exception e) {
            log.debug("{}", e);
            log.error("导出阶段统计Excel表失败！--> {}", e.getMessage());
        }
        try {
            this.sendFile(output, response);
        } catch (IOException e) {
            log.debug("{}", e);
            log.error("文件发送失败！--> {}", e.getMessage());
        }
    }

    private void sendFile(File file, HttpServletResponse response) throws IOException {
        InputStream input = new FileInputStream(file);

        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        response.setStatus(200);

        ServletOutputStream output = response.getOutputStream();

        byte[] bs = new byte[1024];
        int len;
        while ((len = input.read(bs)) != -1) {
            output.write(bs, 0, len);
        }
        output.flush();
        output.close();
        input.close();
    }
}
